package org.projectback.filters.JwtFilters;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtException;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.projectback.entity.AccountEntity.CustomUser;
import org.projectback.utils.Jwt.JwtProperties;
import org.projectback.utils.Jwt.JwtUtils;
import org.projectback.utils.ResultMessage;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

@Slf4j
@Component
public class MainJwtFilter extends OncePerRequestFilter {
    @Resource
    private JwtUtils jwtUtils;
    @Resource
    private JwtProperties jwtProperties;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        //放行refresh请求
        if (request.getRequestURI().equals("/api/test/refresh") || request.getRequestURI().equals("/api/user/login")) {
            filterChain.doFilter(request, response);
            return;
        }
        String token = request.getHeader("Authorization");
        //验证签名
        try {
            //签名有两种状态 一种是无签名 一种是签名异常
            Claims claims = jwtUtils.praseJwt(jwtProperties.getSecretKey(), token);
            if (claims != null) {
                CustomUser customUser = new CustomUser();
                customUser.setUsername(claims.get("name").toString());
                //customUser.setPassword("****");
                customUser.setId(Long.parseLong(claims.get("id").toString()));
                customUser.setRole(claims.get("role").toString());

                UsernamePasswordAuthenticationToken authentication =
                        new UsernamePasswordAuthenticationToken(customUser, null, customUser.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
            filterChain.doFilter(request, response); // ✅ 正常放行
        } catch (JwtException e) {
            // ❌ JWT 解析失败，直接返回 401，不再往下走
            SecurityContextHolder.clearContext();
            response.setStatus(HttpStatus.OK.value());
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json");
            log.info("JWT Token is invalid");
            response.getWriter().write(ResultMessage.unauthorized().toJsonString());
        }
    }
}
